package com.tyrone.leetcode.weekgame;

import java.util.*;

/**
 * @author yelong.xie
 * @date 2024/2/17 23:25
 */
public class LastNonEmptyString {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.lastNonEmptyString("abcd"));
    }

    static class Solution {
        public String lastNonEmptyString(String s) {
            //需要记录最后一次出现的下表
            //记录个数
            int[] index = new int[26];
            int[] num = new int[26];
//            Arrays.fill(num,Integer.MAX_VALUE);
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < s.length(); i++) {
                index[s.charAt(i) - 'a'] = i;
                num[s.charAt(i) - 'a']++;
            }

            for (int i : num) {
                    max = Math.max(i, max);
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < index.length; i++) {
                if (num[i] == max) {
                    map.put(i, index[i]);
                }
            }
            // 将HashMap的键值对转换成List
            List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());

            // 根据值进行排序，升序
            list.sort(Map.Entry.comparingByValue());

            // 创建一个LinkedHashMap，保持排序的顺序
            Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
            for (Map.Entry<Integer, Integer> entry : list) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
            Set<Integer> set = sortedMap.keySet();
            StringBuilder builder = new StringBuilder();
            for (Integer i : set) {
                builder.append((char) (i + 'a'));
            }
            return builder.toString();


        }
    }
}
